package com.android.kmlmrg.services.rest.method;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Application;
import android.os.AsyncTask;
import android.util.Log;

import com.android.kmlmrg.R;
import com.android.kmlmrg.event.RestGetUserEvent;
import com.android.kmlmrg.listener.custom.RestGetUserListener;
import com.android.kmlmrg.listener.custom.UsersListener;
import com.android.kmlmrg.model.ApiSession;
import com.android.kmlmrg.model.User;
import com.android.kmlmrg.services.ServiceController;

/**
 * 
 * @author mayki
 *
 */
public class GetUser extends AsyncTask<Void, Integer, String> {
	
	
	private static final  String LOG_TAG = GetUser.class.getName();
	private static final String METHODE_NAME = "/user";
	private User user;
	private int identifiant;
	private Application vApplication;
	private static  ArrayList<RestGetUserListener> listeners = new ArrayList<RestGetUserListener>();
	private int code;


	public GetUser(Application pApplication , User pUser ) {
		vApplication = pApplication;
		Log.i(LOG_TAG, "START - construct GetUser()");
		identifiant = Integer.parseInt(pUser.getIdentifiant());
		user = pUser;		
		Log.i(LOG_TAG, "END - construct GetUser()");
	}


	protected String doInBackground(Void... sUrl) {
		try {
			String vUrl = this.vApplication.getString(R.string.user_endpoint) + METHODE_NAME + "/" + identifiant;

			ApiSession vApiSession =  ServiceController.getInstance().getApiSession() ;
			JSONObject vJsonObject = new JSONObject();				
			vJsonObject.put(ApiSession.WSCALLERID, vApiSession.getWsCallerId());
			vJsonObject.put(ApiSession.TIMESTAMP, vApiSession.getTimesTamp());
			vJsonObject.put(ApiSession.HASH, vApiSession.getHash());
			String message = vJsonObject.toString();

			URLConnection url = new URL(vUrl).openConnection();
			HttpURLConnection httpcon = (HttpURLConnection) ((new URL(vUrl).openConnection()));

			httpcon.setRequestProperty("Content-Type", "application/json");
			httpcon.setRequestProperty("Accept", "application/json");
			httpcon.setRequestMethod("POST");

			httpcon.setDoInput(true);
			httpcon.setDoOutput(true);
			httpcon.setFixedLengthStreamingMode(message.getBytes().length);
			httpcon.connect();


			OutputStream os = new BufferedOutputStream(httpcon.getOutputStream());
			os.write(message.getBytes());
			//clean up
			os.flush();


			// this will be useful so that you can show a typical 0-100% progress bar
			int fileLength = httpcon.getContentLength();
			
			 code = httpcon.getResponseCode();

			// download the file

			InputStream input = httpcon.getInputStream();
			BufferedReader r = new BufferedReader(new InputStreamReader(input));
			StringBuilder total = new StringBuilder();
			String line;
			while ((line = r.readLine()) != null) {
				total.append(line);
			}
			os.flush();
			os.close();
			input.close();	

			return total.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	@Override
	protected void onPostExecute(String result) {
		Log.i(LOG_TAG, "START - onPostExecute(String result)");
		Log.i(LOG_TAG, "RESPONSE : " + result);
		if (!result.contains("\"errorCode\": \"200\"")) {	
			RestGetUserEvent vEvent = new RestGetUserEvent(this, result);
			fireEvent(vEvent);
		}
		Log.i(LOG_TAG, "END - onPostExecute");
		super.onPostExecute(result);
	}


	private void fireEvent( RestGetUserEvent pEvent ){		
		for(RestGetUserListener listener : listeners){
			listener.resultGetUserRequest( pEvent );
		}
	}

	public static void addListener ( RestGetUserListener pListener ){
		listeners.add(pListener);
	}

	public static void removeListener( UsersListener pListener ){
		listeners.remove(pListener);
	}


}
